const fs = require('fs');
const path = require('path');

function renameAndCleanM3U8Files() {
    // 获取当前目录
    const currentDir = process.cwd();
    
    try {
        // 读取当前目录下的所有文件和文件夹
        const items = fs.readdirSync(currentDir, { withFileTypes: true });
        
        // 筛选出所有文件夹
        const directories = items.filter(item => item.isDirectory());
        
        directories.forEach(directory => {
            const dirName = directory.name;
            const indexPath = path.join(currentDir, dirName, 'index.m3u8');
            const newPath = path.join(currentDir, dirName, `${dirName}.m3u8`);
            
            try {
                // 检查index.m3u8文件是否存在
                fs.accessSync(indexPath, fs.constants.F_OK);
                
                // 读取文件内容
                const data = fs.readFileSync(indexPath, 'utf8');
                
                // 替换 #EXT-X-DISCONTINUITY 包裹的内容
                const cleanedContent = cleanM3U8Content(data);
                
                // 写入清理后的内容到新文件
                fs.writeFileSync(newPath, cleanedContent, 'utf8');
                
                // 删除原文件
                // fs.unlinkSync(indexPath);
                
                console.log(`成功处理: ${dirName}`);
                
            } catch (err) {
                if (err.code === 'ENOENT') {
                    console.log(`在文件夹 ${dirName} 中未找到 index.m3u8 文件`);
                } else {
                    console.error(`处理文件夹 ${dirName} 时出错:`, err.message);
                }
            }
        });
        
        console.log('所有文件处理完成！');
        
    } catch (err) {
        console.error('读取目录失败:', err.message);
    }
}

function cleanM3U8Content(content) {
    // 正则表达式匹配 #EXT-X-DISCONTINUITY 包裹的内容
    let replaceList = [
        {search:/#EXT-X-DISCONTINUITY([\s\S]+?)#EXT-X-DISCONTINUITY\n/g, replace:''},
        {search:/#EXT-X-DISCONTINUITY([\s\S]+?)#EXT-X-ENDLIST/g, replace:'#EXT-X-ENDLIST'},
    ]
    replaceList.forEach(({search, replace})=>{
        content = content.replace(search, replace);
    })
    return content;
}

// 执行函数
renameAndCleanM3U8Files();